package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: itcast_health
 * @create: 2019-10-28 21:45
 * @author: li he
 * @description: 用户会员订单报告
 */
@RestController
@RequestMapping("report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private OrderService orderService;

    @Reference
    private ReportService reportService;

    @RequestMapping("getDateMemberNumber")
    public Result getDateMemberNumber(@RequestBody Date[] value1){
        try {
            System.out.println("value1 = " + value1);
            Map<String,Object> map = memberService.getDateMemberNumber(value1);
            return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    /*获取会员增长折线图*/
    @RequestMapping("getMemberReport")
    public Result getMemberReport() {
        try {
            Map<String, Object> map = memberService.getMemberReport();
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /*获取预约套餐比例图*/
    @RequestMapping("getSetMealReport")
    public Result getSetMealReport() {
        try {
            Map<String, Object> map = orderService.getSetMealReport();
            return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /*获取会员比例图*/
    @RequestMapping("getMemberScaleReport")
    public Result getMemberScaleReport() {
        try {
            Map<String, Object> map = memberService.getMemberScaleReport();
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /*获取运行数据*/
    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData() {

        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConst.GET_BUSINESS_REPORT_FAIL);
        }

    }
    /*
     * 导出excel
     * */
    @RequestMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        //从数据库中读取运营数据
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            /**
            * 1.从数据库中获取数据
            * */
            String reportDate = String.valueOf(map.get("reportDate"));
            String todayNewMember = String.valueOf(map.get("todayNewMember"));
            String totalMember = String.valueOf(map.get("totalMember"));
            String thisWeekNewMember = String.valueOf(map.get("thisWeekNewMember"));
            String thisMonthNewMember = String.valueOf(map.get("thisMonthNewMember"));
            String todayOrderNumber = String.valueOf(map.get("todayOrderNumber"));
            String todayVisitsNumber = String.valueOf(map.get("todayVisitsNumber"));
            String thisWeekOrderNumber = String.valueOf(map.get("thisWeekOrderNumber"));
            String thisWeekVisitsNumber = String.valueOf(map.get("thisWeekVisitsNumber"));
            String thisMonthOrderNumber = String.valueOf(map.get("thisMonthOrderNumber"));
            String thisMonthVisitsNumber = String.valueOf(map.get("thisMonthVisitsNumber"));
            List<Map<String,Object>> hotSetmealMapList = (List<Map<String, Object>>) map.get("hotSetmeal");
            /**
            * 2.获取模板
            * */
            //获取模板的输入流
            InputStream inputStream =  ReportController.class.getClassLoader().getResourceAsStream("template/report_template.xlsx");

            //模板 创建工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

            //获取工作表
            XSSFSheet sheet = workbook.getSheetAt(0);

            /**
             * 2.把数据写到工作表中
             * */
            //日期
            setDate(sheet,2,5,reportDate);
            /*
             * 会员数据统计
             * */
            //今日新增会员
            setDate(sheet,4,5,todayNewMember);
            //总会员数
            setDate(sheet,4,7,totalMember);
            //本周新增会员
            setDate(sheet,5,5,thisWeekNewMember);
            //本月新增会员
            setDate(sheet,5,7,thisMonthNewMember);
            /*
             * 预约到诊数据统计
             * */
            //今日预约数(今天有多少预约)
            setDate(sheet,7,5,todayOrderNumber);
            //今日到到诊数(预约了有多少人来)
            setDate(sheet,7,7,todayVisitsNumber);
            //本周预约数
            setDate(sheet,8,5,thisWeekOrderNumber);
            //本周到诊数
            setDate(sheet,8,7,thisWeekVisitsNumber);
            //本月预约数
            setDate(sheet,9,5,thisMonthOrderNumber);
            //本月到到诊数
            setDate(sheet,9,7,thisMonthVisitsNumber);

            int rowNum = 12;
            for (Map<String, Object> hotSetmealMap : hotSetmealMapList) {
                setDate(sheet,rowNum,4,String.valueOf(hotSetmealMap.get("name")));
                setDate(sheet,rowNum,5,String.valueOf(hotSetmealMap.get("setmeal_count")));
                setDate(sheet,rowNum,6,String.valueOf(hotSetmealMap.get("proportion")));
                rowNum++;
            }

            //把数据写入到excel
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }

    }

    public void setDate(XSSFSheet sheet, int rowNum,int colNum,String data){
        //获取行
        XSSFRow row = sheet.getRow(rowNum);
        //获取单元格(统计日期)
        XSSFCell cell = row.getCell(colNum);
        //给单元格设置数据
        cell.setCellValue(data);
    }
}

/**
reportDate                    :null,  统计时间（现在）
todayNewMember                :0,  今日新增会员数
totalMember                   :0,     总会员数
thisWeekNewMember             :0,  本周新增会员数（本周一 以后）
thisMonthNewMember            :0, 本月新增会员数(本月1号以后)
todayOrderNumber              :0,   今日预约数（今日应该到诊人数）
todayVisitsNumber             :0,   今日到诊数(今日实际来了多少人)
thisWeekOrderNumber           :0,  本周预约人数(范围是周一到周日)
thisWeekVisitsNumber          :0, 本周的实际到诊数（周一以后）
thisMonthOrderNumber          :0,  本月预约人数（范围：1号到本月最后一天）
thisMonthVisitsNumber         :0, 本月的实际到诊人数（1号以后）
hotSetmeal                   （热门套餐（取预约人数最多的前四个）） :[
{name:'阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐',setmeal_count:200,proportion:0.222},
{name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
*/